package com.ross.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 *
 * @author RossZhang
 */
public class UserRealm extends AuthorizingRealm {
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        SimpleAuthorizationInfo sa = new SimpleAuthorizationInfo();
        Object username = principalCollection.getPrimaryPrincipal();
        System.out.println("授权："+username);
        if ("admin".equals(username.toString())){
            sa.addRole("admin");//  添加admin角色
        }
        return sa;
    }

    /**
     * 身份验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("身份验证器");
        //1、根据用户名查询密码
        Object username = token.getPrincipal();  //获取到的是usernamePasswordToken对象中的第一个参数
        String password = "123";

        //2、封装用户的密码
        //第一参数是：用户名
        //第二个参数是：从数据库查询出来的密码
        //第三个参数是：realm名字
        SimpleAuthenticationInfo asci = new SimpleAuthenticationInfo(username,password,getName());

        //3、返回给Shiro
        return asci;
    }
}
